<script setup lang='ts'>
import { computed, defineAsyncComponent, onMounted, ref, watch } from 'vue'
import { useAppStore } from '@/store'
import { useBasicLayout } from '@/hooks/useBasicLayout'
import { PromptStore } from '@/components/common'
import type { UserInfo } from '@/store/modules/user/helper'
import { defaultSetting } from '@/store/modules/user/helper'
import { getToken } from '@/store/modules/auth/helper'
import { getUserInfo } from '@/api/user'

const Setting = defineAsyncComponent(() => import('@/components/common/Setting/index.vue'))

const appStore = useAppStore()

const { isMobile } = useBasicLayout()
const show = ref(false)

const collapsed = computed(() => appStore.siderCollapsed)

onMounted(() => {
  getLoginUserInfo()
})

function handleUpdateCollapsed() {
  appStore.setSiderCollapsed(!collapsed.value)
}

watch(
  isMobile,
  (val) => {
    appStore.setSiderCollapsed(val)
  },
  {
    immediate: true,
    flush: 'post',
  },
)

const userInfo = ref<UserInfo>(defaultSetting().userInfo)
const st = ref({ show: false, showImg: false, menu: [], active: 'chat' })

const isLogin = ref(!!localStorage.getItem('TOKEN'))

/*
 * 获取当前登录用户信息
 */
async function getLoginUserInfo() {
  // 用户未登录,不需要获取用户信息
  if (!getToken())
    return

  const newUserInfo = await getUserInfo()
  if (newUserInfo) {
    if (newUserInfo.data.user.avatar)
      userInfo.value.avatar = newUserInfo.data.user.avatar

    userInfo.value.name = newUserInfo.data.user.nickName
    userInfo.value.userBalance = newUserInfo.data.user.userBalance
    userInfo.value.userName = newUserInfo.data.user.userName
    isLogin.value = true
  }
}
</script>

<template>
  <template v-if="isMobile">
    <div v-show="!collapsed" class="fixed inset-0 z-40 w-full h-full bg-black/40" @click="handleUpdateCollapsed" />
  </template>

  <Setting v-if="st.show" v-model:visible="st.show" />
  <PromptStore v-model:visible="show" />
</template>
